<template>
	<view class="exam-list-container">
		<!-- 顶部Banner -->
		<view class="top-banner">
			<image class="banner-img" src="http://60.205.2.196:8000/static/home/title.png" mode="widthFix"></image>
			<view class="banner-title-box">
				<text class="banner-title-text">错题本</text>
			</view>
		</view>
		
		<!-- 任务中心列表 -->
		<scroll-view 
			class="task-center" 
			scroll-y
			@scrolltolower="loadMore"
			@scroll="handleScroll"
			lower-threshold="100px"
			enable-back-to-top="true">
			
			<!-- 未登录提示 -->
			<view v-if="!isLogin" class="not-login-tip">
				<text>请先登录</text>
				<button @click="goLogin" class="login-btn">立即登录</button>
			</view>
			
			<!-- 加载中 -->
			<view v-else-if="loading" class="loading-tip">
				<text>加载中...</text>
			</view>
			
			<!-- 数据列表 -->
			<view v-else-if="categoryList.length > 0">
				<view class="section-title">
					<view class="title-line"></view>
					<text>任务中心</text>
				</view>
				
				<!-- 可折叠的分类列表 -->
				<view class="category-list">
					<view class="category-item" v-for="(category, index) in categoryList" :key="index">
						<view class="category-header" @click="toggleCategory(index)">
							<text class="category-name">{{ category.name }}</text>
							<image class="arrow-icon" 
								:class="{ expanded: category.expanded }" 
								src="/image/youjiantou.png" 
								mode="aspectFit">
							</image>
						</view>
						
						<!-- 展开的子项 -->
						<view class="sub-items" v-if="category.expanded">
							<view class="sub-item" 
								v-for="(sub, subIndex) in category.children" 
								:key="subIndex"
								@click="goToSubject(sub)">
								<text class="sub-name">{{ sub.name }}</text>
								<image class="sub-arrow" src="/image/youjiantou.png" mode="aspectFit"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 无数据 -->
			<view v-else class="empty-tip">
				<text>暂无任务</text>
			</view>
			
			<!-- 加载更多提示 -->
			<view v-if="categoryList.length > 0" class="load-more-tip">
				<text v-if="loadingMore">⏳ 加载中...</text>
				<text v-else-if="noMore">✅ 没有更多了</text>
				<text v-else>👆 上拉加载更多</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { api } from '@/http.js'

export default {
	data() {
		return {
			categoryList: [],
			loading: false,
			isLogin: false,
			// 分页相关
			pageNum: 1,
			pageSize: 10,
			loadingMore: false,
			noMore: false,
			// 缓存完整数据
			allTasks: []
		}
	},
	onShow() {
		console.log('=== list.vue onShow ===');
		// 检查登录状态
		const token = uni.getStorageSync('token');
		console.log('当前token:', token);
		this.isLogin = !!token;
		
		if (this.isLogin) {
			// 重置分页
			this.pageNum = 1;
			this.noMore = false;
			this.categoryList = [];
			this.allTasks = [];
			this.getCategoryList();
		}
	},
	onReachBottom() {
		console.log('========== 页面触底，触发加载更多 ==========');
		this.loadMore();
	},
	methods: {
		async getCategoryList(isLoadMore = false) {
			if (isLoadMore) {
				this.loadingMore = true;
			} else {
				this.loading = true;
			}
			
			try {
				console.log('=== 开始获取任务列表 ===');
				console.log('当前页码:', this.pageNum, '每页数量:', this.pageSize);
				
				// 如果是首次加载或需要重新获取数据
				if (!isLoadMore || this.allTasks.length === 0) {
					const res = await api.getDashboardTask();
					console.log('任务列表响应 code:', res?.code);
					
					if (res && res.code === 1) {
						const data = res.response;
						console.log('解析数据，任务数量:', data?.length);
						
						if (data && Array.isArray(data) && data.length > 0) {
							// 缓存完整数据
							this.allTasks = data;
							console.log('已缓存所有任务，共', this.allTasks.length, '个');
						} else {
							console.log('响应数据为空');
							this.allTasks = [];
							this.categoryList = [];
							this.noMore = true;
							this.loading = false;
							this.loadingMore = false;
							return;
						}
					} else {
						console.error('API返回错误:', res);
						uni.showToast({
							title: res?.message || '获取数据失败',
							icon: 'none'
						});
						this.loading = false;
						this.loadingMore = false;
						return;
					}
				}
				
				// 从缓存中分页加载数据
				const startIndex = (this.pageNum - 1) * this.pageSize;
				const endIndex = this.pageNum * this.pageSize;
				const pageData = this.allTasks.slice(startIndex, endIndex);
				
				console.log(`分页信息: 总数=${this.allTasks.length}, 当前页=${this.pageNum}, 起始=${startIndex}, 结束=${endIndex}, 本页数量=${pageData.length}`);
				
				if (pageData.length === 0) {
					this.noMore = true;
					if (isLoadMore) {
						uni.showToast({
							title: '没有更多数据了',
							icon: 'none',
							duration: 1500
						});
					}
				} else {
					const newCategoryList = [];
					
					pageData.forEach(task => {
						if (task.paperItems && task.paperItems.length > 0) {
							const children = task.paperItems.map(paper => ({
								id: paper.examPaperId,
								name: paper.examPaperName,
								answerId: paper.examPaperAnswerId,
								status: paper.status
							})).filter(p => p.id);
							
							if (children.length > 0) {
								newCategoryList.push({
									name: task.title,
									expanded: false,
									children: children
								});
								console.log(`任务"${task.title}": ${children.length}个试卷`);
							}
						}
					});
					
					if (isLoadMore) {
						// 追加数据
						this.categoryList = [...this.categoryList, ...newCategoryList];
						console.log('追加数据后，列表共', this.categoryList.length, '个类别');
					} else {
						// 替换数据
						this.categoryList = newCategoryList;
						console.log('首次加载，列表共', this.categoryList.length, '个类别');
					}
					
					   // 检查是否还有更多数据
					   if (pageData.length < this.pageSize) {
						   this.noMore = true;
						   console.log('已加载所有数据');
					   }
				}
			} catch (err) {
				console.error('获取任务列表失败:', err);
				uni.showToast({
					title: '加载失败，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				this.loadingMore = false;
			}
		},
		loadMore() {
			console.log('========== 触发上拉加载更多 [scrolltolower事件] ==========');
			console.log('当前状态:', {
				loadingMore: this.loadingMore,
				noMore: this.noMore,
				loading: this.loading,
				currentPage: this.pageNum,
				totalTasks: this.allTasks.length,
				currentCategories: this.categoryList.length
			});
			
			// 防止重复加载
			if (this.loadingMore || this.noMore || this.loading) {
				console.log('❌ 阻止加载');
				return;
			}
			
			this.pageNum++;
			console.log('✅ 开始加载第', this.pageNum, '页');
			this.getCategoryList(true);
		},
		handleScroll(e) {
			// 根据事件参数的不同结构来处理
			console.log('📍 scroll-view scroll 事件触发');
			console.log('事件对象:', JSON.stringify(e.detail || e).substring(0, 200));
			
			// 尝试从不同的属性中获取滚动信息
			let scrollTop = 0, scrollHeight = 0, clientHeight = 0;
			
			// H5/浏览器环境
			if (e.detail) {
				scrollTop = e.detail.scrollTop || 0;
				scrollHeight = e.detail.scrollHeight || 0;
				clientHeight = e.detail.clientHeight || 0;
			}
			// 其他环境
			else if (e.currentTarget) {
				scrollTop = e.currentTarget.scrollTop || 0;
				scrollHeight = e.currentTarget.scrollHeight || 0;
				clientHeight = e.currentTarget.clientHeight || 0;
			}
			
			const distanceToBottom = scrollHeight - scrollTop - clientHeight;
			
			console.log('滚动计算:', {
				scrollTop,
				scrollHeight,
				clientHeight,
				distanceToBottom
			});
			
			// 判断是否滚动到底部（距离底部150px以内）
			if (distanceToBottom >= 0 && distanceToBottom <= 150) {
				console.log('✅ 距离底部 <= 150px，触发加载更多');
				this.loadMore();
			}
		},
		onScroll(e) {
			console.log('===== scroll-view 滚动事件 =====');
			const scrollTop = e.detail.scrollTop;
			const scrollHeight = e.detail.scrollHeight;
			const clientHeight = e.detail.clientHeight;
			
			console.log('滚动信息:', {
				scrollTop: scrollTop,
				scrollHeight: scrollHeight,
				clientHeight: clientHeight,
				距底部: scrollHeight - scrollTop - clientHeight
			});
			
			// 判断是否滚动到底部（距离底部100px以内）
			if (scrollHeight - scrollTop - clientHeight <= 100) {
				console.log('距离底部小于100px，触发加载更多');
				this.loadMore();
			}
		},
		toggleCategory(index) {
			this.categoryList[index].expanded = !this.categoryList[index].expanded;
		},
		goToSubject(sub) {
			uni.navigateTo({
				url: `/pages/exam/detail?id=${sub.id}&source=list`
			});
		},
		goLogin() {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}
	}
}
</script>

<style lang="scss">
// 禁用页面滚动，只使用 scroll-view 滚动
page {
	height: 100%;
	overflow: hidden;
}
</style>

<style lang="scss" scoped>
.exam-list-container {
	width: 100%;
	height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	
	.top-banner {
		background: linear-gradient(135deg, #87CEEB 0%, #B0E0E6 100%);
		width: 100%;
		padding: 0;
		margin: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		flex-shrink: 0;
		
		.banner-img {
			width: 100%;
			height: auto;
			display: block;
			background: linear-gradient(135deg, #87CEEB 0%, #B0E0E6 100%);
		}
		
		.banner-title-box {
			width: 100%;
			background: #ffffff;
			padding: 20rpx 0;
			text-align: center;
			
			.banner-title-text {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
	
	.task-center {
		flex: 1;
		padding: 30rpx;
		margin-top: 0;
		background: #FFF5F7;
		box-sizing: border-box;
		
		// 未登录提示
		.not-login-tip {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 100rpx 30rpx;
			
			text {
				font-size: 32rpx;
				color: #999;
				margin-bottom: 30rpx;
			}
			
			.login-btn {
				background: #FFB6C1;
				color: #fff;
				border: none;
				border-radius: 30rpx;
				padding: 20rpx 60rpx;
				font-size: 28rpx;
			}
		}
		
		// 加载中提示
		.loading-tip {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 100rpx 30rpx;
			
			text {
				font-size: 28rpx;
				color: #999;
			}
		}
		
		// 无数据提示
		.empty-tip {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 100rpx 30rpx;
			
			text {
				font-size: 28rpx;
				color: #999;
			}
		}
		
		.section-title {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			
			.title-line {
				width: 6rpx;
				height: 32rpx;
				background: #FFB6C1;
				border-radius: 3rpx;
				margin-right: 15rpx;
			}
			
			text {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.category-list {
			.category-item {
				background: #fff;
				border-radius: 20rpx;
				margin-bottom: 20rpx;
				overflow: hidden;
				box-shadow: 0 4rpx 12rpx rgba(255, 182, 193, 0.1);
				
				.category-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					background: #fff;
					transition: background 0.3s;
					
					&:active {
						background: #FFF5F7;
					}
					
					.category-name {
						font-size: 30rpx;
						color: #333;
						font-weight: 500;
					}
					
					.arrow-icon {
						width: 24rpx;
						height: 24rpx;
						transition: transform 0.3s;
						
						&.expanded {
							transform: rotate(90deg);
						}
					}
				}
				
				.sub-items {
					background: #FFF5F7;
					
					.sub-item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 25rpx 30rpx 25rpx 50rpx;
						border-top: 2rpx solid #FFE4E1;
						
						&:active {
							background: #FFE4E1;
						}
						
						.sub-name {
							font-size: 28rpx;
							color: #666;
						}
						
						.sub-arrow {
							width: 20rpx;
							height: 20rpx;
							opacity: 0.5;
						}
					}
				}
			}
		}
		
		// 加载更多提示
		.load-more-tip {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 30rpx 0;
			
			text {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
}
</style>
